import React, { Component } from 'react';
import { Card, message, Button, Tooltip } from 'antd';
import { connect } from 'dva';
import styles from './Cache.less';
@connect(({ loading }) => ({ loading: loading.effects['product/updateProductRegion'] }))
class Cache extends Component {
  state = {
    lastUpdateTime: '',
  };
  componentDidMount() {
    this.fetchLastUpdateTime();
  }
  fetchLastUpdateTime = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'product/queryProductUpdateTime',
    }).then(({ errorCode, data }) => {
      if (errorCode === 0) {
        this.setState({
          lastUpdateTime: data,
        });
      }
    });
  };
  update = () => {
    const { loading, dispatch } = this.props;
    if (loading) return;
    const fetchs = ['product/updateProductRegion', 'dashboard/updateHotAirline'];
    const arr = fetchs.map(val => {
      return dispatch({
        type: val,
      });
    });
    Promise.all(arr).then(res => {
      const allOk = res.find(result => {
        return result.errorCode !== 0;
      });
      if (allOk) {
        message.error(allOk.msg || '更新失败', 10);
      } else {
        message.success('更新成功');
        this.fetchLastUpdateTime();
      }
    });
  };
  render() {
    const { loading } = this.props;
    const { lastUpdateTime } = this.state;
    return (
      <Card bordered={false}>
        <Tooltip title="更新所有产品的范围和热门航线">
          <Button type="primary" loading={loading} onClick={this.update}>
            更新
          </Button>
        </Tooltip>
        <span className={styles.lastUpdateTime}>
          最后更新时间:
          <span className={styles.time}>{lastUpdateTime}</span>
        </span>
      </Card>
    );
  }
}

export default Cache;
